package com.ieslab.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/** 
 * 文件名: BaseHttpServlet <p>
 * 功能说明: Request/Response向下转型总会成功:因为在调用service()方法时,Servlet容器总会预计使用HTTP,从而直接创建并传递HttpServletRequest/HttpServletResponse实例. <p> 
 * 创建时间: 2016年6月16日 下午7:24:04 <p> 
 * @author 郭凯强
 * @version 0.0.1 
 * @since JDK 1.7  
 */
@WebServlet(asyncSupported = true, displayName = "display-baseWebServlet", description = "base httpservlet by guokaiqiang", initParams = {
		@WebInitParam(name = "owner", value = "gkq"), @WebInitParam(name = "goddess", value = "ljl") }, loadOnStartup = 0, name = "baseHttpServlet", urlPatterns = {
		"/base/*", "/first/web/*" })
public class BaseHttpServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	public void init() throws ServletException {
		// super.init();
		System.out
				.println("在第一次请求该Servlet(默认)或容器启动时, Servlet容器就会调用init(), 且只调用一次。GenericServlet实现了Servlet且增加了获取ServletConfig对象的方法");
		ServletConfig servletConfig = this.getServletConfig();
		Enumeration<String> initParameters = servletConfig.getInitParameterNames();
		while (initParameters.hasMoreElements()) {
			String initParameter = initParameters.nextElement();
			System.out.println("==初始化参数" + initParameter + "的值=" + servletConfig.getInitParameter(initParameter));
		}
	}

	@Override
	public void destroy() {
		// super.destroy();
		System.out.println("销毁Servlet时(卸载应用/关闭容器时), 调用该方法");
	}

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public BaseHttpServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * Servlet容器会在每次调用service()方法时创建Response实例并传递给service()形参, HttpServletResponse是Response绑定在HTTP环境下的实例, 其隐藏了将响应发送给浏览器的复杂性
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// request-1:获取请求头
		Enumeration<String> headerNames = request.getHeaderNames();
		while (headerNames.hasMoreElements()) {
			String headerName = (String) headerNames.nextElement();
			System.out.println(headerName + "=" + request.getHeader(headerName));
		}
		System.out.println("remoteAddr=" + request.getRemoteAddr());
		System.out.println("contextPath=" + request.getContextPath());
		System.out.println("dateHeader" + request.getDateHeader("date"));
		// request-2:获取请求参数?
		Map<String, String[]> parameterMap = request.getParameterMap();
		// request.getParameterNames();
		// request.getParameterValues("Xxx");
		for (Entry<String, String[]> entry : parameterMap.entrySet()) {
			System.out.println(entry.getKey() + "==>" + entry.getValue());
		}
		Enumeration<String> queryParameters = request.getParameterNames();
		while (queryParameters.hasMoreElements()) {
			String parameter = queryParameters.nextElement();
			System.out.println(parameter + "=" + request.getParameter(parameter));
		}
		// request-3:请求转发/包含=Request提供了getRequestDispatcher()来获取一个RequestDispatcher,
		// 并由其提供请求转发/请求包含功能
		// RequestDispatcher requestDispatcher =
		// request.getRequestDispatcher("/index.jsp");
		// requestDispatcher.forward(request, response);
		// request-4:域对象传递数据
		request.setAttribute("myname", "gkq");
		Enumeration<String> attrNames = request.getAttributeNames();
		while (attrNames.hasMoreElements()) {
			String attrName = (String) attrNames.nextElement();
			System.out.println(attrName + "---" + request.getAttribute(attrName));
			// request.removeAttribute(attrName);
		}
		// response-1:设置响应状态码
		// response.setStatus(404);
		// response.sendError(404, "nothing!");
		// response-2:设置响应头信息
		// response-2.1:设置禁用浏览器缓存(Cache-Control,pragma,expires)
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("pragma", "no-cache");
		response.setDateHeader("expires", -1);
		// response-2.2:设置重定向
		// response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
		// response.setHeader("Location", "http://www.baidu.com");
		// HttpServletResponse还提供了另外一种重定向的方式, 直接使用sendRedirect()方法, 避免了以上的步骤
		response.sendRedirect("http://www.baidu.com");
		// response-2.3:设置响应正文
		// response.getOutputStream();
		// response.getWriter();
		// servletContext-1:域对象
		ServletContext servletContext = this.getServletContext();
		// servletContext.getAttributeNames();
		// servletContext-2:获取针对本应用程序的公共初始化参数
		Enumeration<String> parameters = servletContext.getInitParameterNames();
		while (parameters.hasMoreElements()) {
			String parameter = parameters.nextElement();
			System.out.println("contextParameter:" + parameter + "的值=" + servletContext.getInitParameter(parameter));
		}
		// servletContext-3:获取资源
		String realPath = servletContext.getRealPath("/index.jsp");
		System.out.println("/index.jsp的realPath为：" + realPath);
		URL url = servletContext.getResource("/WEB-INF/web.xml");
		System.out.println("/WEB-INF/web.xml的资源路径：" + url.toString());
		Set<String> resourcePaths = servletContext.getResourcePaths("/");
		System.out.println("===============根路径'/'下的直接文件或直接子目录路径=============");
		Iterator<String> iterator = resourcePaths.iterator();
		while (iterator.hasNext()) {
			String resourcePath = iterator.next();
			System.out.println(resourcePath);
		}
		InputStream inputStream = servletContext.getResourceAsStream("/WEB-INF/spring-base.xml");
		System.out.println(inputStream.getClass());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		System.out.println("-----POST----");
		Enumeration<String> queryParameters = request.getParameterNames();
		while (queryParameters.hasMoreElements()) {
			String parameter = queryParameters.nextElement();
			System.out.println(parameter + "=" + request.getParameter(parameter));
		}
		HttpSession session = request.getSession();
		BaseSessionBeanListener beanListener = new BaseSessionBeanListener();
		beanListener.setName("sessionId=" + session.getId());
		beanListener.setId(1);
		request.getSession().setAttribute("bean", beanListener);
		System.out.println("-----POST-----");
	}
}
